package com.vchello.service.impl.message;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.vchello.bean.message.Message;
import com.vchello.dao.message.MessageDao;
import com.vchello.service.message.MessageService;

/**
 * 
 * @author power
 *
 */
@Service(value = "messageService")
public class MessageServiceImpl extends ServiceImpl<MessageDao, Message> implements MessageService {

	@Autowired
	private MessageDao messageDao;
	
	@Override
	public Integer saveMessage(Message message) {
		return messageDao.insert(message);
	}

	@Override
	public Page<Message> findMessageByStatus(Page<Message> page, int receiveUserId) {
		Wrapper<Message> wrapper = new EntityWrapper<Message>();
		wrapper.eq("receiveUserId", receiveUserId).eq("status", 0);
		page.setOrderByField("createTime DESC");
		return selectPage(page, wrapper);
	}

	@Override
	public Page<Message> findMessageBySend(Page<Message> page, int sendUserId) {
		Wrapper<Message> wrapper = new EntityWrapper<Message>();
		wrapper.eq("send_user_id", sendUserId).eq("status", 1);
		page.setOrderByField("create_time DESC");
		return selectPage(page, wrapper);
	}

	@Override
	public Page<Message> findMessageByReceive(Page<Message> page, int receiveUserId) {
		Wrapper<Message> wrapper = new EntityWrapper<Message>();
		wrapper.eq("receive_user_id", receiveUserId).eq("status", 1);
		page.setOrderByField("create_time DESC");
		return selectPage(page, wrapper);
	}

	@Override
	public int receiveMessageCount(int userId) {
		Wrapper<Message> wrapper = new EntityWrapper<Message>();
		wrapper.in("receive_user_id", new Object[]{userId, 0}).eq("status", 1).eq("is_read", 1);
		return messageDao.selectList(wrapper).size();
	}

	@Override
	public boolean updateRead(int userId) {
		return messageDao.updateRead(userId);
	}

	@Override
	public boolean deleteMessage(Message message) {
		try {
			messageDao.deleteById(message);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public boolean updateStatus(int id) {
		return messageDao.updateStatus(id);
	}

	@Override
	public Message findById(int id) {
		return messageDao.selectById(id);
	}

	@Override
	public List<Message> findMessageByPage(Page<Message> page, Message message) {
		Wrapper<Message> wrapper = new EntityWrapper<Message>(message);
		return messageDao.selectPage(page, wrapper);
	}

}
